package com.learn.algorithm_09;

import java.util.Stack;

/**
 * 用两个栈（先进后出）实现队列（先进先出）
 *
 * https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
 *
 * @author gatts, 2022/2/8 12:51
 */
public class CQueue {

    // 用来添加元素
    private final Stack<Integer> pushStack;
    // 用来删除元素
    private final Stack<Integer> popStack;

    public CQueue() {
        pushStack = new Stack<>();
        popStack = new Stack<>();
    }

    public void appendTail(int value) {
        pushStack.push(value);
    }

    public synchronized int deleteHead() {
        if (popStack.isEmpty()) {
            if (pushStack.isEmpty()) {
                return -1;
            }
            while (!pushStack.isEmpty()) {
                popStack.push(pushStack.pop());
            }
        }
        return popStack.pop();
    }

    public boolean isEmpty() {
        return pushStack.isEmpty() && popStack.isEmpty();
    }

    public static void main(String[] args) {
        CQueue queue = new CQueue();
        queue.appendTail(1);
        queue.appendTail(2);
        queue.appendTail(3);
        queue.appendTail(4);

        while (!queue.isEmpty()) {
            System.out.println(queue.deleteHead());
        }
    }

}
